package com.linjacy.httpproject.excelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.linjacy.httpproject.entity.User;
import com.linjacy.httpproject.mapper.UserMapper;
import com.linjacy.httpproject.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.stream.Collectors;

public class UserDataListener extends AnalysisEventListener<User> {

    private Logger logger =  LoggerFactory.getLogger(UserDataListener.class);

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 缓存的数据
     */
    private List<User> cachedDataList = new ArrayList<>(BATCH_COUNT);

    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private UserMapper userMapper;


    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param
     */
    public UserDataListener() {
        this.userMapper = (UserMapper) SpringUtil.getApplicationContext().getBean(UserMapper.class);
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(User data, AnalysisContext context) {
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = new ArrayList<>(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }

    public User handlerHead(Map<Integer, String> data){
        User user = new User();
        Optional.ofNullable(data).ifPresent(t -> {
            String userName = t.get(1);
            String password = t.get(2);
            user.setUserName(userName);
            user.setPassword(password);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            user.setUserId(UUID.randomUUID().toString().replaceAll("-",""));
        });
        return user;
    }
    /**
     * 加上存储数据库
     */
    private void saveData() {
        cachedDataList.stream().peek(user -> {
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            user.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));
        }).collect(Collectors.toList());
        for (User user : cachedDataList) {
            logger.info(user.toString());
//            userMapper.insert(user);
        }
    }
}
